package cn.jietuo.juc.c_002_account;

import java.util.concurrent.TimeUnit;

/**
 * @author zhangx & jietuo_zx@163.com
 * @version 1.0
 * @date 2020/5/4
 * @description: 面试题：模拟银行账户
 * 对业务写方法加锁
 * 对业务读方法不加锁
 * 对业务读方法不加锁
 * 容易产生脏读问题（dirtyRead）
 */
public class Account {

    private String name;

    private double balance;

    public synchronized void setBalance(String name, double balance) {
        this.name = name;

        try {
            TimeUnit.MICROSECONDS.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        this.balance = balance;
        System.out.println(balance);
    }

    public synchronized double getBalance() {
        return this.balance;
    }

    public static void main(String[] args) {
        Account account = new Account();
        new Thread(() -> {
            account.setBalance("张山", 100.0);
        }).start();

        new Thread(() -> {
            double balance = account.getBalance();
            System.out.println(balance);
        }).start();
    }
}
